package storage;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class storageMgr {
	private String homedir = System.getProperty("user.home") + "\\smallllldb";
	
	private int pageSize = 4 * 1024 * 1024;
	private int scale = 1024;
	
	public int pageSize(){return pageSize;}
	public int scale(){return scale;}
	
	public storageMgr(){} 
	
	public int changeLoc(String newPath){
		homedir = newPath;
		return 1;
	}
	
	public  int newDB(String dbname){
		File dbFile = new File(homedir, dbname + ".dbs");
		if( !dbFile.exists() ){
			try {
				dbFile.createNewFile();
			} catch (IOException e) {
				throw new RuntimeException( dbname + " can not create ");
			}
		}
		else throw new RuntimeException( dbname + " already exists ");
		return 1;
	}
	
	public  int canOpen(String dbname){
		File dbFile = new File(homedir, dbname + ".dbs");
		if ( !dbFile.exists() ){
			throw new RuntimeException( dbname + " not exists ");
		}
		return 1;
	}
	/**
	 * Attention: whether the db is in use must be tested before here.
	 */
	public  int canClose(String dbname){
		File dbFile = new File(homedir, dbname + ".dbs");
		if ( !dbFile.exists() ){
			throw new RuntimeException( dbname + " not exists ");
		}
		return 1;
	}
	
	public  int destroyDB(String dbname){
		File dbFile = new File(homedir, dbname + ".dbs");
		if ( !dbFile.exists() ){
			throw new RuntimeException( dbname + " not exists ");
		}
		else{
			if (!dbFile.delete())
				throw new RuntimeException( dbname + " cannot destroy ");
		}
		return 1;
	}
	
	public  int writePage(String dbname, int pid, ByteBuffer bb){
		try{
			bb.rewind();
			FileChannel fc = (new RandomAccessFile(homedir + dbname + ".dbs", "rws").getChannel());
			fc.write(bb, pid*pageSize);
		}
		catch(IOException e){
			throw new RuntimeException("cannot read page " + pid );
		}
		return 1;
	}
	
	public  int readPage(String dbname, int pid, ByteBuffer bb){
		try{
			bb.clear();
			FileChannel fc = (new RandomAccessFile( homedir + dbname + ".dbs", "rws").getChannel());
			fc.read(bb, pid*pageSize);
		}
		catch(IOException e){
			throw new RuntimeException("cannot read page " + pid );
		}
		return 1;
	}
	
}
